package com.inspiration.controller;

import cn.hutool.core.io.FileUtil;
import com.inspiration.entity.R;
import com.inspiration.config.DBBackup;
import com.inspiration.utils.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author : Vincent.jiao
 * @Date : 2023/11/4 17:49
 * @Version : 1.0
 */
@RequestMapping("/system")
@Controller
public class SystemController {
    @Autowired
    DBBackup dbBackup;

    @RequestMapping("/backup/list")
    @ResponseBody
    public Object backupFileList() throws FileNotFoundException {
        List<String> list = new LinkedList<>();
        File backupFile = new File(PathUtils.getDBBackup());
        if(!backupFile.exists()) {
            backupFile.mkdirs();
        }

        for (File file : backupFile.listFiles()) {
            list.add(file.getName());
        }

        return R.ok("list", list);
    }

    @RequestMapping("/backup/down")
    public void downBackup(String fileName, HttpServletResponse response) throws IOException {
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);

        File file = new File(PathUtils.getDBBackup(), fileName);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        OutputStream out = null;
        InputStream in = null;

        try {
            out = response.getOutputStream();
            in = FileUtil.getInputStream(file);
            int len = 0;

            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            response.setStatus(200);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
            in.close();
        }
    }
}
